﻿using famails.bus;
using famails.common;
using famails.dto;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Web;
using System.Web.Script.Services;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace famails.BackEnd.page
{
    public partial class EmailFillter : System.Web.UI.Page
    {
        DataTable group = null;
        static log4net.ILog logs = log4net.LogManager.GetLogger("ErrorRollingLogFileAppender");
        static UserLoginDTO userLogin = null;
        protected void Page_Load(object sender, EventArgs e)
        {
            userLogin = getUserLogin();
            if (!IsPostBack)
            {
                try{
                    LoadSubGroup();
                }
                catch (Exception)
                {

                }
            }
        }

        private void LoadSubGroup()
        {
            try
            {
                MailGroupBUS mgBUS = new MailGroupBUS(); ;
                DataTable MailGroup = new DataTable();
                if (Session["us-login"] != null)
                {
                    if (getUserLogin().DepartmentId == 1)
                    {
                        MailGroup = mgBUS.GetAllNew();
                    }
                    else
                    {
                        MailGroup = mgBUS.GetMailGroupByUserId(getUserLogin().UserId);
                    }
                    if (MailGroup.Rows.Count > 0)
                    {
                        createTableMail();
                        DataRow rowE = null;
                        if (getUserLogin().DepartmentId == 1)
                        {
                            rowE = group.NewRow();
                            rowE["Id"] = 0;
                            rowE["Name"] = "Tất cả";
                            group.Rows.Add(rowE);
                        }
                        foreach (DataRow rowItem in MailGroup.Rows)
                        {
                            rowE = group.NewRow();
                            rowE["Id"] = rowItem["Id"];
                            rowE["Name"] = rowItem["Name"];
                            group.Rows.Add(rowE);
                        }
                    }
                    this.drlSubGroup.DataSource = group;
                    this.drlSubGroup.DataTextField = "Name";
                    this.drlSubGroup.DataValueField = "Id";
                    this.drlSubGroup.DataBind();
                }
            }
            catch (Exception ex)
            {

                logs.Error(userLogin.Username + "-Client - LoadSubGroup", ex);
            }

            // pnSearch.Visible = true;
            // btnSearch.Visible = false;
        }

        private void createTableMail()
        {
            group = new DataTable("group");
            DataColumn Id = new DataColumn("Id");
            Id.DataType = System.Type.GetType("System.Int32");
            DataColumn Name = new DataColumn("Name");
            DataColumn[] key = { Id };
            group.Columns.Add(Id);
            group.Columns.Add(Name);
            group.PrimaryKey = key;
        }

        private UserLoginDTO getUserLogin()
        {
            if (Session["us-login"] != null)
            {
                return (UserLoginDTO)Session["us-login"];
            }
            else Response.Redirect("~");//test confict
            return null;
        }
       

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static string AddEmail(string ids, int groupid)
        {
            int err = 0, count = 0;
            try
            {
                DetailGroupDTO dsgDTO = new DetailGroupDTO();
                DetailGroupBUS dsgBUS = new DetailGroupBUS(); ;
                string[] listid = ids.Split(',');
                foreach (string id in listid)
                {
                    decimal emailid = 0;
                    decimal.TryParse(id, out emailid);
                    if (emailid > 0)
                    {
                        dsgDTO.GroupID = groupid;
                        dsgDTO.CustomerID = emailid;
                        dsgDTO.CountReceivedMail = 0;
                        dsgDTO.LastReceivedMail = DateTime.Now;
                        if (dsgBUS.GetByID(dsgDTO.GroupID, dsgDTO.CustomerID).Rows.Count > 0)
                        {
                            err++;
                        }
                        else
                        {
                            dsgBUS.tblDetailGroup_insert(dsgDTO);
                            count++;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                logs.Error(userLogin.Username + "-ListEvent - btnDelete_Click", ex);
            }
            return "Bạn đã thêm thành công " + count + " khách hàng vào nhóm và trùng :" + err.ToString() + " khách hàng.";
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static List<CustomerDTO> Search(string name, string phone, string email, int group)
        {
            userLogin = (UserLoginDTO)HttpContext.Current.Session["us-login"];
            //string name = "", phone = "h", email = ""; int group = -1;
            CustomerBUS ctBUS = new CustomerBUS();
            DataTable customerBySelect = ctBUS.GetAllByUserAssignTo(userLogin.UserId, group, name, email, phone);
            List<CustomerDTO> result = new List<CustomerDTO>();
            CustomerDTO item = new CustomerDTO();
            foreach (DataRow dr in customerBySelect.Rows)
            {
                item = new CustomerDTO();
                item.Id = Convert.ToInt32(dr["id"] + "");
                item.Name = dr["Name"] + "";
                item.Email = dr["Email"] + "";
                item.Phone = dr["Phone"] + "";
                item.Job = dr["Job"] + "";
                item.Address = dr["Address"] + "";
                item.Company = dr["Company"] + "";
                if (dr["BirthDay"] + "" != "")
                    item.BirthDay = Convert.ToDateTime(dr["BirthDay"] + "");
                item.Status = Convert.ToBoolean(dr["recivedEmail"]) ? "Còn hoạt động" : "Mail chết";
                result.Add(item);
            }

            return result;
        }
    }

}